use std::io::Write;

use async_trait::async_trait;
use rcmd_core::{clap::ArgMatches, log};
use surf::http::convert::json;

use crate::{global::DpmError, subcmd::walk_pkginstall_path};

use super::{basecmd::BaseCmd, get_exec_path};

struct List {
    path: String,
}

impl List {
    fn new(path: &str) -> Self {
        List {
            path: String::from(path),
        }
    }
}

#[async_trait]
impl BaseCmd for List {
    async fn run(&self) -> Result<(), DpmError> {
        let ret = walk_pkginstall_path(&self.path);
        log::debug!("walk result is {:?}", ret);
        std::io::stdout().write_all(json!(ret.unwrap_or_default()).to_string().as_bytes())?;
        Ok(())
    }
}

pub async fn handle(_subm: &ArgMatches) {
    let p = get_exec_path();
    let cmd = &List::new(p.as_str());
    cmd.run().await.unwrap_or_else(|e| {
        log::error!("{}", e.to_string().as_str());
    });
}

#[test]
fn test_list() {
    use std::env::temp_dir;
    let path_tmp = temp_dir();
    //chk init
    let path_str = path_tmp.display().to_string();
    let cmd = List { path: path_str };
    let _ = cmd.run();
}
